package com.source.auto;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.source.auto.model.JsonConfigInfo;
import com.source.auto.model.ProjectInfo;
import com.source.auto.utils.BizUtil;
import com.source.auto.utils.FileUtil;
import com.source.auto.utils.GitUtil;
import com.source.auto.utils.LogUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * @author wangchangjie
 * @date 2025/1/15 11:03
 */


public class CollectBranchChange {

    public static void main(String[] args) {
        try {
            matchProjectByBranch();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void matchProjectByBranch() throws Exception {

        // 匹配到的分支集合
        List<String> matchedBranches = new ArrayList<>();
        // 匹配到的远程仓库地址集合
        List<String> repoUrls = new ArrayList<>();
        // 匹配到的本地仓库地址集合
        List<String> localGitRepos = new ArrayList<>();


        JsonConfigInfo configInfo = new JsonConfigInfo();




        // 设置父目录路径
        String parentDirectory = "";
        // 设置关键词(只能匹配到一个分支) TODO:如果匹配到多个分支要提示用户完全输入
        String keyword = "";

        // 设置json文件路径
        String projectJsonPath = "src/main/java/com/source/auto/config/projectInfo.json";

        // 读取json信息，再匹配项目
        JsonConfigInfo jsonConfigInfo = FileUtil.loadJsonConfig(projectJsonPath);

        if (jsonConfigInfo == null) {
            if (StrUtil.isEmpty(parentDirectory)){
                LogUtil.printf("请输入项目父目录路径：");
                Scanner scanner = new Scanner(System.in);
                parentDirectory = scanner.next();
            }
        }
        Boolean needStuff = false;
        if (jsonConfigInfo != null){
            if (StrUtil.isBlank(jsonConfigInfo.getParentDirectory())){
                LogUtil.printf("请输入项目父目录路径：");
                Scanner scanner = new Scanner(System.in);
                parentDirectory = scanner.next();
                needStuff = true;
            }else {
                while (true){
                    LogUtil.printf("是否需要继续使用上次的项目父目录路径：{} ? (y/n)", jsonConfigInfo.getParentDirectory());
                    Scanner scanner = new Scanner(System.in);
                    String next = scanner.next();
                    if("y".equals(next)){
                        parentDirectory = jsonConfigInfo.getParentDirectory();
                        break;
                    }else if ("n".equals(next)){
                        LogUtil.printf("请输入新的项目父目录路径：");
                        Scanner scanner2 = new Scanner(System.in);
                        parentDirectory = scanner2.next();
                        needStuff = true;
                        break;
                    }
                }
            }
        }

        configInfo.setBranchKeyWords(keyword);
        configInfo.setParentDirectory(parentDirectory);
        configInfo.setProjectConfigs(new ArrayList<>());
        if (jsonConfigInfo != null){
            jsonConfigInfo.setParentDirectory(parentDirectory);
            jsonConfigInfo.setBranchKeyWords(keyword);
            if (needStuff){
                // 重写json文件保存到本地
                String jsonStr = JSONUtil.toJsonStr(jsonConfigInfo);
                LogUtil.printf(jsonStr);
                FileUtil.overwriteFile(projectJsonPath, jsonStr);
            }
        }


        LogUtil.info("开始扫描文件夹...");
        // 递归查找所有的 .git 文件夹
        List<String> gitRepos = FileUtil.findGitRepositories(new File(
            StrUtil.isEmpty(parentDirectory) ? jsonConfigInfo.getParentDirectory()
                : parentDirectory));

        Set<String> matchAllGitBranchList = new HashSet<>();
        for (String repoPath : gitRepos) {
            // 1、获取每个 Git 仓库的所有分支
            List<String> branches = GitUtil.getGitBranches(repoPath);
            matchAllGitBranchList.addAll(branches);
        }
        List<String> matchAllGitBranchListTemp = new ArrayList<>(matchAllGitBranchList);


        LogUtil.printf("");
        LogUtil.printf("请输入您需要匹配的分支：(例：*mas* 可匹配 i_master | *可模糊搜索)");
        while (true){
            Scanner scanner = new Scanner(System.in);
            keyword = scanner.next();
            String key = keyword.trim();

            boolean leftLike = key.startsWith("*");
            boolean rightLike = key.endsWith("*");
            if (leftLike) {
                key = key.substring(1);
            }
            if (rightLike) {
                key = key.substring(0, key.length() - 1);
            }

            String finalKey = key;
            List<String> matched = matchAllGitBranchListTemp.stream()
                .filter(f -> {
                    if (leftLike && rightLike) {
                        return  f.contains(finalKey);
                    }
                    if (leftLike) {
                        return  f.endsWith(finalKey);
                    }
                    if (rightLike) {
                        return f.startsWith(finalKey);
                    }
                    return f.equals(finalKey);
                }).collect(
                    Collectors.toList());
            if (matched.size() == 1) {
                LogUtil.printf("匹配成功：{}",matched.get(0));
                keyword = matched.get(0);
                break;
            }else if (matched.size() > 1){
                LogUtil.printf("匹配到多个分支，请从下面的分支中选择再输入：");
                matched.forEach(f-> LogUtil.printf(" - {}",f));
            }else {
                LogUtil.printf("未匹配到分支，请重新输入：");
            }
        }

        AtomicInteger count = new AtomicInteger();
        for (String repoPath : gitRepos) {
            count.getAndIncrement();
            LogUtil.infoPrint(
                "解析本地仓库 {} 次：{} \r", count.get(),repoPath);

            // 1、获取每个 Git 仓库的所有分支
            List<String> branches = GitUtil.getGitBranches(repoPath);
            // 2、匹配分支名称中包含关键词的分支
            List<String> matched = GitUtil.matchBranches(branches, keyword);
            if (matched.isEmpty()) {
                continue;
            }
            matchedBranches.addAll(matched);
            repoUrls.add(GitUtil.getRepoUrl(repoPath));
            localGitRepos.add(repoPath);

            if (jsonConfigInfo == null) {
                ProjectInfo projectInfo = BizUtil.refreshJsonConfigInfo(repoPath);
                if (CollUtil.isNotEmpty(projectInfo.getServices())) {
                    configInfo.getProjectConfigs().add(projectInfo);
                }
            }
        }

        if (jsonConfigInfo == null && CollUtil.isNotEmpty(configInfo.getProjectConfigs())) {
            jsonConfigInfo = configInfo;
            // 重写json文件保存到本地
            String jsonStr = JSONUtil.toJsonStr(jsonConfigInfo);
            LogUtil.printf(jsonStr);
            FileUtil.overwriteFile(projectJsonPath, jsonStr);
        }

        // 打印匹配的分支及其对应的仓库地址
        BizUtil.printInfo(matchedBranches, repoUrls);

        // 打印需要归档的内容
        BizUtil.printArchiveInfo(projectJsonPath,jsonConfigInfo, matchedBranches, localGitRepos);
    }


}